<!--
 * @Description: 
 * @version: 
 * @Author: 尹鹏孝
 * @Date: 2022-06-24 13:43:57
 * @LastEditors: 尹鹏孝
 * @LastEditTime: 2022-06-24 13:58:51
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>对Function的思考</title>
</head>
<body>
    <script>
        //一、通过function解析字符串为js可执行代码。这种情况可以使用eval来替换，但是Function更加安全
    var script = "var name=`${name}`; var age=`${age}`;console.log(this.cun); function showName(){console.log(name)}" +
            " function showAge(){console.log(age)}"

        var fanHui = "{showName,showAge}";
        let str = script + '\nreturn ' + fanHui + ';';

        let k = { cun: "zhoWa" };
        let obj = (new Function("name,age", str).bind(k))("xuHaiTao", 36);
        console.log(obj.showName(), obj.showAge());

    //二、通过Function创建一个函数，不常用----------------------
    let fc= new Function('var total = 0,args = arguments;for (var i = 0; i < args.length; i++ ) {total += args[ i ];}return console.log(total); total;');
            fc(100,200);
            var myFunction = new Function('users', 'salary', 'return console.log(users * salary); users * salary'); 
            myFunction(100,200);
    </script>
</body>
</html>